import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/store'
import _this from '../main.js'
import menu from './menu'
import axios from '@/utils/axios'
import { setCookie } from '@/utils/cookie'
import { getLoginStatus } from 'api'

Vue.use(Router)

let isAddRoutes = false // 是否已添加路由

const router = new Router({
  mode: 'history',
  base: '/',
  routes: []
})

function getShopInfo(directory) {
  return new Promise(async (resolve, reject) => {
    try {
      const { ResultSet } = await axios.post(getLoginStatus)
      resolve(data)
    } catch (err) {
      console.log(err)
      reject(err)
    }
  })
}

router.beforeEach(async (to, from, next) => {
  if (!isAddRoutes) {
    // 生成动态路由
    const list = []
    list.push({
      path: '*',
      redirect: { name: 'index' }
    })
    menu.forEach(item => {
      list.push({ ...item, path: `${item.path}` })
    })
    router.addRoutes(list)
    isAddRoutes = true
    next({ ...to, replace: true })
  } else {
    if (!store.getters.name && to.name !== 'login' && to.name !== 'survey') store.dispatch('loadUserInfo', { next, to })
    else next()
  }
})
// router.afterEach((to, from) => {
//   _this.$modal.hide('printOrder')
// })
// console.log(Router.prototype)
// const originalReplace = Router.prototype.replace
// Router.prototype.replace = function replace(location) {
//   return originalReplace.call(this, location).catch(err => err)
// }

export default router
